<template>
  <div class="permission-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="page-title">
        <el-icon class="title-icon"><Key /></el-icon>
        <span>权限管理</span>
      </div>
      <div class="page-description">
        管理系统权限信息，包括权限的增删改查、状态管理等操作
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Search /></el-icon>
            <span>搜索条件</span>
          </div>
        </div>
      </template>
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="权限名称">
          <el-input
            v-model="searchForm.permissionName"
            placeholder="请输入权限名称"
            clearable
            style="width: 200px"
            :prefix-icon="Key"
          />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input
            v-model="searchForm.permissionCode"
            placeholder="请输入权限编码"
            clearable
            style="width: 200px"
            :prefix-icon="Key"
          />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
            <el-option label="接口" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="handleReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-wrapper">
        <div class="left-operations">
          <!-- 新增权限按钮 -->
          <el-button 
            type="primary" 
            @click="handleAdd" 
            :icon="Plus"
          >
            新增权限
          </el-button>
          
          <!-- 批量启用按钮 -->
          <el-button 
            type="success" 
            @click="handleBatchEnable" 
            :icon="Check" 
            :disabled="!hasSelected"
          >
            批量启用
          </el-button>
          
          <!-- 批量禁用按钮 -->
          <el-button 
            type="warning" 
            @click="handleBatchDisable" 
            :icon="Close" 
            :disabled="!hasSelected"
          >
            批量禁用
          </el-button>
          
          <!-- 批量删除按钮 -->
          <el-button 
            type="danger" 
            @click="handleBatchDelete" 
            :icon="Delete" 
            :disabled="!hasSelected"
          >
            批量删除
          </el-button>
        </div>
        <div class="right-operations">
          <el-button @click="handleRefresh" :icon="Refresh" circle />
        </div>
      </div>
    </el-card>

    <!-- 权限表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><List /></el-icon>
            <span>权限列表</span>
            <el-tag type="info" size="small">{{ pagination.total }} 条记录</el-tag>
          </div>
          <div class="header-right">
            <el-switch
              v-model="tableConfig.stripe"
              active-text="斑马纹"
              inactive-text="普通"
              size="small"
            />
            <el-switch
              v-model="tableConfig.border"
              active-text="边框"
              inactive-text="无边框"
              size="small"
            />
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="permissionList"
        :border="tableConfig.border"
        :stripe="tableConfig.stripe"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <!-- <el-table-column prop="id" label="ID" width="80" /> -->
        <el-table-column prop="permissionName" label="权限名称" min-width="150" />
        <el-table-column prop="permissionCode" label="权限编码" min-width="150" />
        <el-table-column prop="type" label="权限类型" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" effect="dark">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parentName" label="父权限" min-width="120">
          <template #default="{ row }">
            <span v-if="row.parentName">{{ row.parentName }}</span>
            <el-tag v-else type="info" size="small" effect="plain">顶级权限</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="150" show-overflow-tooltip />
        <el-table-column prop="component" label="组件" min-width="150" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" min-width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon" :class="row.icon" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="dark">
              <el-icon v-if="row.status === 1"><Check /></el-icon>
              <el-icon v-else><Close /></el-icon>
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="visible" label="可见性" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.visible === 1 ? 'success' : 'warning'" effect="dark">
              {{ row.visible === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" min-width="80" align="center" />
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="{ row }">
            <div class="time-cell">
              <el-icon><Clock /></el-icon>
              <span>{{ formatDateTime(row.createTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <!-- 编辑权限按钮 -->
              <el-tooltip content="编辑权限" placement="top">
                <el-button 
                  type="primary" 
                  size="small" 
                  circle
                  @click="handleEdit(row)" 
                  :icon="Edit"
                />
              </el-tooltip>
              
              <!-- 启用/禁用权限按钮 -->
              <el-tooltip :content="row.status === 1 ? '禁用权限' : '启用权限'" placement="top">
                <el-button
                  :type="row.status === 1 ? 'warning' : 'success'"
                  size="small"
                  circle
                  @click="handleToggleStatus(row)"
                  :icon="row.status === 1 ? Close : Check"
                />
              </el-tooltip>
              
              <!-- 查看详情按钮 -->
              <el-tooltip content="查看详情" placement="top">
                <el-button 
                  type="info" 
                  size="small" 
                  circle
                  @click="handleView(row)" 
                  :icon="View"
                />
              </el-tooltip>
              
              <!-- 删除权限按钮 -->
              <el-tooltip content="删除权限" placement="top">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="handleDelete(row)" 
                  :icon="Delete"
                />
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="7"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 权限表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionFormRules"
        label-width="100px"
        class="permission-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限名称" prop="permissionName">
              <el-input 
                v-model="permissionForm.permissionName" 
                placeholder="请输入权限名称"
                :prefix-icon="Key"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="permissionCode">
              <el-input 
                v-model="permissionForm.permissionCode" 
                placeholder="请输入权限编码"
                :prefix-icon="Key"
                :disabled="!!permissionForm.id"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="权限类型" prop="type">
              <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
                <el-option label="菜单" :value="1" />
                <el-option label="按钮" :value="2" />
                <el-option label="接口" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="父权限" prop="parentId">
              <el-select v-model="permissionForm.parentId" placeholder="请选择父权限" clearable style="width: 100%">
                <el-option label="顶级权限" :value="0" />
                <el-option
                  v-for="permission in parentPermissions"
                  :key="permission.id"
                  :label="permission.permissionName"
                  :value="permission.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="路径" prop="path">
              <el-input 
                v-model="permissionForm.path" 
                placeholder="请输入路径"
                :prefix-icon="Link"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组件" prop="component">
              <el-input 
                v-model="permissionForm.component" 
                placeholder="请输入组件"
                :prefix-icon="Document"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图标" prop="icon">
              <el-input 
                v-model="permissionForm.icon" 
                placeholder="请输入图标"
                :prefix-icon="Picture"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortOrder">
              <el-input-number 
                v-model="permissionForm.sortOrder" 
                :min="0" 
                :max="999"
                placeholder="请输入排序值"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="permissionForm.status">
                <el-radio :label="1">
                  <el-icon><Check /></el-icon>
                  启用
                </el-radio>
                <el-radio :label="0">
                  <el-icon><Close /></el-icon>
                  禁用
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可见性" prop="visible">
              <el-radio-group v-model="permissionForm.visible">
                <el-radio :label="1">
                  <el-icon><View /></el-icon>
                  显示
                </el-radio>
                <el-radio :label="0">
                  <el-icon><Hide /></el-icon>
                  隐藏
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="权限详情"
      width="700px"
      :close-on-click-modal="false"
    >
      <div v-if="currentPermission" class="permission-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="权限ID">{{ currentPermission.id }}</el-descriptions-item>
          <el-descriptions-item label="权限名称">{{ currentPermission.permissionName }}</el-descriptions-item>
          <el-descriptions-item label="权限编码">{{ currentPermission.permissionCode }}</el-descriptions-item>
          <el-descriptions-item label="权限类型">
            <el-tag :type="getTypeTagType(currentPermission.type)">
              {{ getTypeText(currentPermission.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="父权限">{{ currentPermission.parentName || '顶级权限' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentPermission.status === 1 ? 'success' : 'danger'">
              {{ currentPermission.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="可见性">
            <el-tag :type="currentPermission.visible === 1 ? 'success' : 'warning'">
              {{ currentPermission.visible === 1 ? '显示' : '隐藏' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ currentPermission.sortOrder }}</el-descriptions-item>
          <el-descriptions-item label="路径" :span="2">{{ currentPermission.path || '-' }}</el-descriptions-item>
          <el-descriptions-item label="组件" :span="2">{{ currentPermission.component || '-' }}</el-descriptions-item>
          <el-descriptions-item label="图标" :span="2">{{ currentPermission.icon || '-' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(currentPermission.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间" :span="2">
            {{ formatDateTime(currentPermission.updateTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Key, Search, Refresh, Plus, Check, Close, Delete, 
  List, Edit, View, Clock, Link, Document, Picture, Hide 
} from '@element-plus/icons-vue'
import { permissionApi } from '@/api/permission'
import { useAuthStore } from '@/stores/auth'

// 获取权限存储
const authStore = useAuthStore()

// 权限检查方法
const hasPermission = (permission) => {
  return authStore.hasPermission(permission)
}

// 检查是否有任何权限
const hasAnyPermission = (permissions) => {
  return authStore.hasAnyPermission(permissions)
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const permissionFormRef = ref()
const selectedPermissions = ref([])
const currentPermission = ref(null)
const parentPermissions = ref([])

// 表格配置
const tableConfig = reactive({
  stripe: true,
  border: true
})

// 搜索表单
const searchForm = reactive({
  permissionName: '',
  permissionCode: '',
  type: null,
  status: null
})

// 权限表单
const permissionForm = reactive({
  id: null,
  permissionName: '',
  permissionCode: '',
  type: 1,
  parentId: 0,
  path: '',
  component: '',
  icon: '',
  sortOrder: 0,
  visible: 1,
  status: 1
})

// 表单验证规则
const permissionFormRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 100, message: '权限编码长度在 2 到 100 个字符', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_:]*$/, message: '权限编码只能包含小写字母、数字、下划线和冒号，且必须以字母开头', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 分页信息
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

// 权限列表
const permissionList = ref([])

// 计算属性
const hasSelected = computed(() => selectedPermissions.value.length > 0)

// 生命周期
onMounted(() => {
  fetchPermissionList()
  fetchParentPermissions()
})

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      orderBy: 'id',
      orderType: 'asc',
      ...searchForm
    }
    
    const response = await permissionApi.getPermissionList(params)
    if (response.data.code === 200) {
      permissionList.value = response.data.data.list
      pagination.total = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取权限列表失败')
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 获取父权限列表
const fetchParentPermissions = async () => {
  try {
    const response = await permissionApi.getAllPermissions()
    if (response.data.code === 200) {
      parentPermissions.value = response.data.data
    }
  } catch (error) {
    console.error('获取父权限列表失败:', error)
  }
}

// 获取权限类型文本
const getTypeText = (type) => {
  const typeMap = {
    1: '菜单',
    2: '按钮',
    3: '接口'
  }
  return typeMap[type] || '未知'
}

// 获取权限类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    1: 'primary',
    2: 'success',
    3: 'warning'
  }
  return typeMap[type] || 'info'
}

// 搜索
const handleSearch = () => {
  pagination.pageNum = 1
  fetchPermissionList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    permissionName: '',
    permissionCode: '',
    type: null,
    status: null
  })
  pagination.pageNum = 1
  fetchPermissionList()
}

// 刷新
const handleRefresh = () => {
  fetchPermissionList()
  ElMessage.success('刷新成功')
}

// 新增权限
const handleAdd = () => {
  // 检查新增权限
  if (!authStore.hasPermission('system:permission:add')) {
    ElMessage.warning('您没有新增权限的权限')
    return
  }
  
  dialogTitle.value = '新增权限'
  resetPermissionForm()
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:permission:edit')) {
    ElMessage.warning('您没有编辑权限的权限')
    return
  }
  
  dialogTitle.value = '编辑权限'
  Object.assign(permissionForm, {
    id: row.id,
    permissionName: row.permissionName,
    permissionCode: row.permissionCode,
    type: row.type,
    parentId: row.parentId || 0,
    path: row.path || '',
    component: row.component || '',
    icon: row.icon || '',
    sortOrder: row.sortOrder,
    visible: row.visible,
    status: row.status
  })
  dialogVisible.value = true
}

// 查看权限详情
const handleView = (row) => {
  // 检查查询权限
  if (!authStore.hasPermission('system:permission:query')) {
    ElMessage.warning('您没有查看权限详情的权限')
    return
  }
  
  currentPermission.value = row
  detailDialogVisible.value = true
}

// 删除权限
const handleDelete = async (row) => {
  // 检查删除权限
  if (!authStore.hasPermission('system:permission:delete')) {
    ElMessage.warning('您没有删除权限的权限')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除权限 "${row.permissionName}" 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )
    
    const response = await permissionApi.deletePermission(row.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchPermissionList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 切换权限状态
const handleToggleStatus = async (row) => {
  // 检查编辑权限
  if (!authStore.hasPermission('system:permission:edit')) {
    ElMessage.warning('您没有修改权限状态的权限')
    return
  }
  
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}权限 "${row.permissionName}" 吗？`,
      `确认${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await permissionApi.updatePermissionStatus(row.id, newStatus)
    if (response.data.code === 200) {
      ElMessage.success(`${statusText}成功`)
      fetchPermissionList()
    } else {
      ElMessage.error(response.data.message || `${statusText}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${statusText}权限失败:`, error)
      ElMessage.error(`${statusText}失败`)
    }
  }
}

// 批量操作
const handleBatchEnable = async () => {
  await handleBatchStatus(1, '启用')
}

const handleBatchDisable = async () => {
  await handleBatchStatus(0, '禁用')
}

const handleBatchStatus = async (status, statusText) => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请先选择要操作的权限')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要${statusText}选中的 ${selectedPermissions.value.length} 个权限吗？`,
      `批量${statusText}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const promises = selectedPermissions.value.map(permission => 
      permissionApi.updatePermissionStatus(permission.id, status)
    )
    
    await Promise.all(promises)
    ElMessage.success(`批量${statusText}成功`)
    fetchPermissionList()
    selectedPermissions.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`批量${statusText}失败:`, error)
      ElMessage.error(`批量${statusText}失败`)
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedPermissions.value.length === 0) {
    ElMessage.warning('请先选择要删除的权限')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPermissions.value.length} 个权限吗？此操作不可恢复！`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }
    )

    const promises = selectedPermissions.value.map(permission => 
      permissionApi.deletePermission(permission.id)
    )
    
    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    fetchPermissionList()
    selectedPermissions.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedPermissions.value = selection
}

// 提交表单
const handleSubmit = async () => {
  try {
    await permissionFormRef.value.validate()
    submitLoading.value = true
    
    const api = permissionForm.id ? permissionApi.updatePermission : permissionApi.addPermission
    const response = await api(permissionForm)
    
    if (response.data.code === 200) {
      ElMessage.success(permissionForm.id ? '更新成功' : '新增成功')
      dialogVisible.value = false
      fetchPermissionList()
      fetchParentPermissions() // 刷新父权限列表
    } else {
      ElMessage.error(response.data.message || (permissionForm.id ? '更新失败' : '新增失败'))
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置权限表单
const resetPermissionForm = () => {
  Object.assign(permissionForm, {
    id: null,
    permissionName: '',
    permissionCode: '',
    type: 1,
    parentId: 0,
    path: '',
    component: '',
    icon: '',
    sortOrder: 0,
    visible: 1,
    status: 1
  })
  nextTick(() => {
    permissionFormRef.value?.clearValidate()
  })
}

// 关闭对话框
const handleDialogClose = () => {
  resetPermissionForm()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageNum = 1
  fetchPermissionList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.pageNum = page
  fetchPermissionList()
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.title-icon {
  margin-right: 10px;
  font-size: 28px;
}

.page-description {
  font-size: 14px;
  opacity: 0.9;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}

.header-icon {
  font-size: 16px;
  color: var(--el-color-primary);
  margin-right: 2px;
}

.card-header .header-left span {
  font-weight: 500;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.operation-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-operations {
  display: flex;
  gap: 10px;
}

.right-operations {
  display: flex;
  gap: 10px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.operation-buttons .el-button {
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.operation-buttons .el-button--primary {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
}

.operation-buttons .el-button--primary:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d5aa0 100%);
}

.operation-buttons .el-button--success {
  background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
  border: none;
}

.operation-buttons .el-button--success:hover {
  background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
}

.operation-buttons .el-button--warning {
  background: linear-gradient(135deg, #e6a23c 0%, #cf9236 100%);
  border: none;
}

.operation-buttons .el-button--warning:hover {
  background: linear-gradient(135deg, #cf9236 0%, #b88230 100%);
}

.operation-buttons .el-button--info {
  background: linear-gradient(135deg, #909399 0%, #82848a 100%);
  border: none;
}

.operation-buttons .el-button--info:hover {
  background: linear-gradient(135deg, #82848a 0%, #73767a 100%);
}

.operation-buttons .el-button--danger {
  background: linear-gradient(135deg, #f56c6c 0%, #dc4e4e 100%);
  border: none;
}

.operation-buttons .el-button--danger:hover {
  background: linear-gradient(135deg, #dc4e4e 0%, #c23e3e 100%);
}

/* 操作列样式优化 */
:deep(.el-table .el-table__cell:last-child) {
  padding: 8px 12px;
}

:deep(.el-table .el-table__cell:last-child .cell) {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 工具提示样式优化 */
:deep(.el-tooltip__popper) {
  font-size: 12px;
  padding: 6px 10px;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
}

:deep(.el-pagination) {
  --el-pagination-font-size: 14px;
  --el-pagination-button-margin: 0 4px;
  --el-pagination-button-padding: 0 8px;
}

:deep(.el-pagination .el-pagination__total) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin: 0 16px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: var(--el-color-primary);
  color: white;
  font-weight: 600;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
  margin: 0 4px;
}

:deep(.el-pagination .el-pagination__jump) {
  margin-left: 16px;
}

.permission-form {
  padding: 20px 0;
}

.permission-detail {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 10px;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-table .el-table__header-wrapper) {
  background-color: #fafafa;
}

:deep(.el-table .el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table .el-table__body td) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table .el-table__body tr:hover > td) {
  background-color: #f5f7fa;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-management {
    padding: 10px;
  }
  
  .operation-wrapper {
    flex-direction: column;
    gap: 15px;
  }
  
  .left-operations,
  .right-operations {
    width: 100%;
    justify-content: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 